package com.yupi.springbootinit.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.mapper.UserInterfaceInfoMapper;
import com.yupi.springbootinit.service.UserInterfaceInfoService;
import model.entity.UserInterfaceInfo;
import org.springframework.stereotype.Service;


/**
* @author 25169
* @description 针对表【user_interface_info(用户接口调用关系)】的数据库操作Service实现
* @createDate 2023-03-12 14:40:22
*/
@Service
public class UserInterfaceInfoServiceImpl extends ServiceImpl<UserInterfaceInfoMapper, UserInterfaceInfo>
    implements UserInterfaceInfoService {

    private static final Object lock = new Object();

    @Override
    public void validUserInterfaceInfo(UserInterfaceInfo userInterfaceInfo, boolean add) {
        if (userInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 创建时，参数不能为空
        if (add) {
            if(userInterfaceInfo.getInterfaceInfoId()<=0 || userInterfaceInfo.getUserId()<=0){
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"接口或用户不存在");
            }
        }
        if(userInterfaceInfo.getLeftNum()<0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"剩余次数不能小于0");
        }
    }


    @Override
    public boolean invoke(long interfaceInfoId, long userId) {
        if(interfaceInfoId<=0 || userId<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        LambdaUpdateWrapper<UserInterfaceInfo> updateWrapper=new LambdaUpdateWrapper<>();
        updateWrapper.eq(UserInterfaceInfo::getInterfaceInfoId,interfaceInfoId);
        updateWrapper.eq(UserInterfaceInfo::getUserId,userId);
        updateWrapper.gt(UserInterfaceInfo::getLeftNum,0);
        //updateWrapper.ge(UserInterfaceInfo::getLeftNum,0);
        // TODO 并发处理
        synchronized (lock){
            updateWrapper.setSql("leftNum= leftNum-1,totalNum=totalNum+1");
        }

        return this.update(updateWrapper);
    }
}




